import { InputService } from './currency.service';

export class InputHandler {
  private inputService: InputService;
  private onModelChange: Function;
  private onModelTouched: Function;
  private htmlInputElement: HTMLInputElement;

  //
  constructor(htmlInputElement: HTMLInputElement, options: any) {
    this.inputService = new InputService(htmlInputElement, options);
    this.htmlInputElement = htmlInputElement;
  }

  private isReadOnly() {
    return this.htmlInputElement && this.htmlInputElement.readOnly;
  }
  handleCompositionEnd() {
    if (this.inputService.canInputMoreNumbers) {
      this.inputService.addNumber('');
    }
    this.onModelChange(this.inputService.value);
  }
  handleKeypress(e: any): void {
    if (this.isReadOnly()) {
      return;
    }

    const key = e.key;

    // const aKeysFilter = ['Tab', 'Enter', 'End', 'Home', 'ArrowLeft', 'ArrowUp', 'ArrowRight', 'ArrowDown'];
    // if (aKeysFilter.includes(key)) {
    //   return;
    // }
    console.log(key);
    const aKeysFilter = ['Backspace', 'Delete', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
    if (!aKeysFilter.includes(key)) {
      event.preventDefault();
      return;
    }

    if (this.inputService.canInputMoreNumbers && !isNaN(this.inputService.value)) {
      this.inputService.addNumber(key);
    }
    event.preventDefault();
    this.onModelChange(this.inputService.value);
  }

  /**
   * 键盘按下
   * @param event
   */
  handleKeydown(e: any): void {
    if (this.isReadOnly()) {
      return;
    }
    const key = e.key;
    if (key === 'Backspace' || key === 'Delete') {
      e.preventDefault();
      const selectionRangeLength = Math.abs(
        this.inputService.inputSelection.selectionEnd - this.inputService.inputSelection.selectionStart
      );
      // 等于0 赋值空值
      if (selectionRangeLength === this.inputService.rawValue.length || this.inputService.value === 0) {
        this.setValue(null);
        this.onModelChange(this.inputService.value);
      }

      if (selectionRangeLength === 0 && !isNaN(this.inputService.value)) {
        this.inputService.removeNumber(key);
        this.onModelChange(this.inputService.value);
      }

      if (selectionRangeLength !== 0 && !isNaN(this.inputService.value)) {
        this.inputService.removeNumber(key);
        this.onModelChange(this.inputService.value);
      }
    }
  }

  // 双向绑定用

  getOnModelChange(): Function {
    return this.onModelChange;
  }

  setOnModelChange(callbackFunction: Function): void {
    this.onModelChange = callbackFunction;
  }

  getOnModelTouched(): Function {
    return this.onModelTouched;
  }

  setOnModelTouched(callbackFunction: Function) {
    this.onModelTouched = callbackFunction;
  }

  // 双向绑定用

  setValue(value: any): void {
    this.inputService.value = value;
  }
}
